package com.xnyzc.lhy.mis.service.impl.cms.allocation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.ListToTreeUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.mis.entity.param.cms.OfficeParam;
import com.xnyzc.lhy.mis.entity.sidebar.OaCUserOffice;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.mis.mapper.sidebar.OaCUserOfficeMapper;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserOfficeMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.mis.service.cms.allocation.AllocationService;
import com.xnyzc.lhy.mis.service.cms.util.IOaSysGetOfficeIdListService;
import com.xnyzc.lhy.mis.entity.user.OaDUser;
import com.xnyzc.lhy.mis.entity.user.OaDUserOffice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 机构相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-08-08
 */
@Service
public class AllocationServiceImpl implements AllocationService {

    @Autowired
    private OaCUserOfficeMapper oaCUserOfficeMapper;

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    @Autowired
    private OaDUserOfficeMapper oaDUserOfficeMapper;

    @Autowired
    private IOaSysGetOfficeIdListService iOaSysGetOfficeIdListService;

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private OaSysVehicleMapper oaSysVehicleMapper;

    /**
     * 用户、司机机构关联数据
     *
     * @return
     */
    @Override
    public Rv getUserOfficeAllocationData() {
        Long sysUserId = TokenUtil.getTokenUserId();
        // 获取当前角色可查看机构
        List<Long> selectOfficeIdList = iOaSysGetOfficeIdListService.selectOfficeIdList(sysUserId);
        List<Map<String, Object>> mapList = new ArrayList<>();
        // 查询机构
        QueryWrapper<OaSysOffice> cUserQueryWrapper = new QueryWrapper<>();
        cUserQueryWrapper.in(OaSysOffice.OFFICE_ID, selectOfficeIdList);
        List<OaSysOffice> officeList = oaSysOfficeMapper.selectList(cUserQueryWrapper);
        for (int i = 0; i < officeList.size(); i++) {
            OaSysOffice e = officeList.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getOfficeId());
            map.put("pId", e.getParentId());
            map.put("name", e.getName());
            mapList.add(map);
        }
        JSONArray resultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(mapList)), "id", "pId", "children");
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 用户关联机构
     *
     * @return
     */
    @Override
    public Rv getUserOfficeAllocation(OfficeParam officeParam) {
        Long sysUserId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        List<Long> userIdList = officeParam.getUserIdList();
        Long officeId = officeParam.getOfficeId();
        // 选择的机构
        OaSysOffice sysOffice = oaSysOfficeMapper.selectById(officeId);
        Date date = new Date();
        List<Long> modifiedUsreIdList = new ArrayList<>();
        QueryWrapper<OaCUserOffice> cUserQueryWrapper = new QueryWrapper<>();
        cUserQueryWrapper.in(OaCUserOffice.USER_ID, userIdList);
        List<OaCUserOffice> cUserOfficeList = oaCUserOfficeMapper.selectList(cUserQueryWrapper);
        if (!cUserOfficeList.isEmpty()) {
            for (OaCUserOffice office : cUserOfficeList) {
                office.setUpdateTime(date);
                office.setUpdateUser(sysUserId);
                office.setOfficeId(officeId);
                office.setTag(tag);
                oaCUserOfficeMapper.updateById(office);
                modifiedUsreIdList.add(office.getUserId());
            }
            userIdList.removeAll(modifiedUsreIdList);
            if (!userIdList.isEmpty()) {
                for (Long userId : userIdList) {
                    OaCUserOffice office = new OaCUserOffice();
                    office.setLinkedId(IDUtil.nextId());
                    office.setOfficeId(officeId);
                    office.setUserId(userId);
                    office.setUpdateUser(sysUserId);
                    office.setUpdateTime(date);
                    office.setCreateTime(date);
                    office.setCreateUser(sysUserId);
                    office.setTag(tag);
                    oaCUserOfficeMapper.insert(office);
                }
            }
        }
        return Rv.wrap(EErrorCode.success);
    }

    /**
     * 司机关联机构
     *
     * @return
     */
    @Override
    public Rv getDriverOfficeAllocation(OfficeParam officeParam) {
        String tag = TokenUtil.getTag();
        Long sysUserId = TokenUtil.getTokenUserId();
        List<Long> userIdList = officeParam.getUserIdList();
        Long officeId = officeParam.getOfficeId();
        if(CheckUtil.objIsEmpty(officeId)||CheckUtil.objIsEmpty(userIdList)){
            throw PangException.create(EErrorCode.missingArg);
        }
        // 选择的机构
        OaSysOffice sysOffice = oaSysOfficeMapper.selectById(officeId);
        // 父级机构
        OaSysOffice parentSysOffice = oaSysOfficeMapper.selectById(sysOffice.getParentId());
        String parentId = parentSysOffice.getParentId();
        String parentIds = parentSysOffice.getParentIds();
        Date date = new Date();
        QueryWrapper<OaDUserOffice> dUserQueryWrapper = new QueryWrapper<>();
        dUserQueryWrapper.in(OaDUserOffice.DRIVER_ID, userIdList);
        List<OaDUserOffice> dUserOfficeList = oaDUserOfficeMapper.selectList(dUserQueryWrapper);
        List<Long> modifiedUsreIdList = new ArrayList<>();
        if (!dUserOfficeList.isEmpty()) {
            for (OaDUserOffice office : dUserOfficeList) {
                office.setOfficeId(officeId);
                office.setUpdateTime(date);
                office.setUpdateUser(sysUserId);
                office.setTag(tag);
                oaDUserOfficeMapper.updateById(office);
                modifiedUsreIdList.add(office.getDriverId());
            }
        }
        userIdList.removeAll(modifiedUsreIdList);
        if (!userIdList.isEmpty()) {
            for (Long userId : userIdList) {
                OaDUserOffice office = new OaDUserOffice();
                office.setLinkedId(IDUtil.nextId());
                office.setOfficeId(officeId);
                office.setDriverId(userId);
                office.setUpdateUser(sysUserId);
                office.setUpdateTime(date);
                office.setCreateTime(date);
                office.setCreateUser(sysUserId);
                office.setTag(tag);
                oaDUserOfficeMapper.insert(office);
            }
        }
        return Rv.wrap(EErrorCode.success);
    }

    /**
     * 查询所有司机定位信息
     *
     * @return
     */
    @Override
    public Rv getVehicleGpsList() {
        List<OaDVehicleGps> list = new ArrayList<>();
        Set<String> keys = redisCommon.keys(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + "*");
        if (CheckUtil.collectionIsEmpty(keys)) {
            throw PangException.create(EErrorCode.unData);
        }
        for (String key : keys) {
            String str = redisCommon.getStr(key);
            OaDVehicleGps oaDVehicleGps = JSON.parseObject(str, OaDVehicleGps.class);
            if (CheckUtil.objIsEmpty(oaDVehicleGps)) {
                continue;
            }
            if (CheckUtil.objIsEmpty(oaDVehicleGps.getDriverId())) {
                continue;
            }
            System.out.println("==================================================================" + oaDVehicleGps);
            OaDUser oaDUser = oaDUserMapper.selectById(oaDVehicleGps.getDriverId());
            oaDVehicleGps.setDriverName(oaDUser.getDriverName());
            oaDVehicleGps.setPhone(oaDUser.getDriverPhone());
            // 车牌号
            OaSysVehicle oaSysVehicle = oaSysVehicleMapper.selectById(oaDVehicleGps.getVehId());
            oaDVehicleGps.setMotorcadeNum(oaSysVehicle.getVehNo());
            list.add(oaDVehicleGps);
        }
        if (CheckUtil.collectionIsEmpty(list)) {
            throw PangException.create(EErrorCode.unData);
        }
        return Rv.wrap(list);
    }

}
